use sea_orm::{ColumnTrait, DatabaseConnection, EntityTrait, QueryFilter};
use sky_pojo::{
    dto::address::SearchDTO,
    entities::address_book::{self, ActiveModel},
};

pub async fn list(
    db: &DatabaseConnection,
    dto: SearchDTO,
) -> Result<Vec<address_book::Model>, sea_orm::DbErr> {
    let mut stmt =
        address_book::Entity::find().filter(address_book::Column::UserId.eq(dto.user_id));

    if dto.is_default == true {
        stmt = stmt.filter(address_book::Column::IsDefault.eq(1));
    }

    stmt.all(db).await
}

pub async fn insert(
    db: &DatabaseConnection,
    model: address_book::ActiveModel,
) -> Result<address_book::Model, sea_orm::DbErr> {
    address_book::Entity::insert(model)
        .exec_with_returning(db)
        .await
}

pub async fn get_by_id(
    db: &DatabaseConnection,
    id: i64,
) -> Result<address_book::Model, sea_orm::DbErr> {
    match address_book::Entity::find_by_id(id).one(db).await {
        Ok(model) => {
            if model.is_none() {
                return Err(sea_orm::DbErr::RecordNotFound(format!(
                    "query by id {}",
                    id.to_string()
                )));
            }

            return Ok(model.unwrap());
        }
        Err(e) => Err(e),
    }
}

pub async fn update(
    db: &DatabaseConnection,
    model: address_book::ActiveModel,
    user_id: i64,
) -> Result<address_book::Model, sea_orm::DbErr> {
    address_book::Entity::update(model)
        .filter(address_book::Column::UserId.eq(user_id))
        .exec(db)
        .await
}

pub async fn update_is_default_by_user_id(
    db: &DatabaseConnection,
    id: i64,
    user_id: i64,
) -> Result<address_book::Model, sea_orm::DbErr> {
    address_book::Entity::update(ActiveModel {
        id: sea_orm::ActiveValue::set(id),
        is_default: sea_orm::ActiveValue::Set(1),
        ..Default::default()
    })
    .filter(address_book::Column::UserId.eq(user_id))
    .exec(db)
    .await
}

pub async fn delete_by_id(
    db: &DatabaseConnection,
    id: i64,
    user_id: i64,
) -> Result<sea_orm::DeleteResult, sea_orm::DbErr> {
    address_book::Entity::delete_by_id(id)
        .filter(address_book::Column::UserId.eq(user_id))
        .exec(db)
        .await
}
